package com.ruoyi.web.controller.tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.form.BuzTaskAddData;
import com.ruoyi.system.domain.form.UserTaskAddData;
import com.ruoyi.system.mapper.BuzTaskAwardsJackpotMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.tool.Area;
import com.ruoyi.web.controller.tool.model.VO_AwardInfo;
import com.ruoyi.web.core.config.JDCloudOSS;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.IYxSmsService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.coobird.thumbnailator.Thumbnails;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.AmazonS3;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.map.HashedMap;

@Api("APP接口API")
@RestController
@RequestMapping("/appApi")
@EnableAsync
public class ApiController extends BaseController {

    @Autowired
    private IYxSmsService tSmsService;
    
    /**阿里云短信接口*/
    @Autowired
    private SendSmsDemo sendSmsDemo;
    
    /**京东云短信接口*/
    @Autowired
	private SmsSender smsSender;
    
    @Autowired
    private IBuzMemberService buzMemberService;
    @Autowired
    private IBaseAreaService baseAreaService;
    @Autowired
    private IBuzTaskService buzTaskService;
    @Autowired
    private IBuzTaskUserService iBuzTaskUserService;
    @Autowired
    private IBuzTaskAreaService iBuzTaskAreaService;
    
    @Autowired
    private IBuzNewsService buzNewsService;
    
    @Autowired
    private BuzTaskAwardsJackpotMapper buzTaskAwardsJackpotMapper;

    @ApiOperation("获取地区信息")
    @GetMapping("/getAreaList")
    public TableDataInfo getAreaTree() {
        List<Area> result = baseAreaService.getCityArea().stream().map(e -> {
            if (e.getParentId() == 100000) {
                e.setParentId(0);
            }
            return new Area(e);
        }).collect(Collectors.toList());
        return getDataTable(result);
    }
    
    @ApiOperation("获取当前日期")
    @GetMapping("/getCurrentDate")
    public AjaxResult getCurrentDate() {
    	String today= DateUtil.today();
        return AjaxResult.success(today);
    }

    @ApiOperation("保存用户信息")
    @PostMapping("/saveMember")
    public AjaxResult saveMember(@RequestBody BuzMember buzMember) {
    	// 获取OpenId
    	//String openId = getUsername();
    	System.out.println(buzMember.toString());
    	
    	if(buzMember.getPhone()!=null&&!buzMember.getPhone().equals("")) {
	    	//判断当前手机号是否绑定别的微信号
	    	BuzMember memberQuery=new BuzMember();
	    	memberQuery.setOpenId(buzMember.getOpenId());
	    	memberQuery.setPhone(buzMember.getPhone());
	    	List<BuzMember> memberList2=buzMemberService.selectBuzMemberListOtherPhone(memberQuery);
	    	if(memberList2!=null&&memberList2.size()>0) {
	    		return error("手机号码已绑定别的微信号，请使用别的手机号码");
	    	}
    	}
    	
        return success(buzTaskService.saveOrUpdateMember(buzMember));
    }
    
    
    /**
	 * 修改个人信息头像
	 * @param token
	 * @param file
	 * @return
	 */
	@ApiOperation("修改个人信息头像")
	@PostMapping("/myInfoAvatarUpdate")
	public AjaxResult myInfoAvatarUpdate(String openId,
										 @RequestParam(required = false, value = "file") MultipartFile file) {
		
		BuzMember member=new BuzMember();
    	member.setOpenId(openId);
    	List<BuzMember> memberList=buzMemberService.selectBuzMemberList(member);
    	System.out.println("-----------member Size---"+memberList.size());
    	if(memberList!=null&&memberList.size()>0) {
    		member=memberList.get(0);
    		System.out.println("-----------member Id---"+member.getId());
    	}
		
		if(member.getId()==null||member.getId().trim().equals("")) {
    		return error("会员信息为空");
    	}
		
		if (file != null) {
			String img = "";
			String imgName = "";
			String imgPath = "";
			String imgType = "";
			
			img = file.getOriginalFilename();
			int i = img.lastIndexOf('.');
			if (i <= 0) {
				return AjaxResult.error("文件格式不正确！");
			}
			imgType = img.substring(img.lastIndexOf(".")+1);
			if(!"jpg".equals(imgType.toLowerCase()) && !"png".equals(imgType.toLowerCase())
					&& !"bmp".equals(imgType.toLowerCase())&& !"gif".equals(imgType.toLowerCase())
					&& !"tif".equals(imgType.toLowerCase())&& !"jpeg".equals(imgType.toLowerCase())&& !"tiff".equals(imgType.toLowerCase())){
				return AjaxResult.error("文件格式不正确！");
			}
			imgName = ImgFileRename.imgFileRename(img);
			

			imgPath = RuoYiConfig.getUploadPath()+"/userHead/" + member.getOpenId();
			File dosc = new File(imgPath);
			if (!dosc.exists()) {
				dosc.mkdirs();
			}
			imgPath = imgPath + "/" + imgName;

			dosc = new File(imgPath);

			String userAvatarURL = null;
			try {
				file.transferTo(dosc);
				
				//再次判断上传的文件是否真的图片
				InputStream is = new FileInputStream(imgPath);
				if(!ImgUtils.isPicture(is)) {
					return AjaxResult.error("文件格式不正确！");
				}
				
				// 原先的图片压缩方式
				// strConfig.commpressPicForScale(imgPath, imgPath, 500, 0.5);
				// 更改过后的图片压缩方式
				// 原始头像保存路径
				userAvatarURL = commpressPicForScale(imgPath, imgPath, 100, 0.5);

			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			/** 更改过后保存的是存储在京东云OSS上的头像访问地址 */
			// 更改后的保存方式
			if (null != userAvatarURL) {
				member.setAvatar(userAvatarURL);
			}
			
			buzMemberService.updateBuzMember(member);
			
			return AjaxResult.success(userAvatarURL);
		}else {
			return AjaxResult.error("文件内容为空！");
		}
		
	}
    
	
	//图片压缩

		/**
		 * @param srcPath     原图片地址
		 * @param desPath     目标图片地址
		 * @param desFileSize 指定图片大小,单位kb
		 * @param accuracy    精度,递归压缩的比率,建议小于0.9
		 * @return
		 */
		public static String commpressPicForScale(String srcPath, String desPath, long desFileSize, double accuracy) {
			try {
				File srcFile = new File(srcPath);
				long srcFilesize = srcFile.length();
				System.out.println("原图片:" + srcPath + ",大小:" + srcFilesize / 1024 + "kb");
				Thumbnails.of(srcPath).scale(0.9).outputQuality(accuracy).toFile(desPath);
				//递归压缩,直到目标文件大小小于desFileSize
				commpressPicCycle(desPath, desFileSize, accuracy);
				/*
				 * File desFile = new File(desPath);
				 * System.out.println("目标图片:" + desPath + ",大小" + desFile.length()/1024 + "kb"); System.out.println("图片压缩完成!");
				 */
			} catch (Exception e) {
				e.printStackTrace();
			}
			// 将用户上传的头像上传到京东云OSS

            // 将生成的二维码图片上传到京东云OSS
           JDCloudOSS oss = new JDCloudOSS();
           String avatar = oss.uploadFileJDCloud(desPath);
			
			// 并返回访问的Url地址
			return avatar;
		}
		
		public static void commpressPicCycle(String desPath, long desFileSize, double accuracy) throws IOException {
			File imgFile = new File(desPath);
			long fileSize = imgFile.length();
			fileSize = fileSize / 1024;
			System.err.println(fileSize);
			//判断大小,如果小于desFileSize,不压缩,如果大于等于desFileSize,压缩
			if (fileSize <= desFileSize) {
				return;
			}
			Thumbnails.of(desPath).scale(0.5).outputQuality(accuracy).toFile(desPath);
			//如果不满足要求,递归直至满足小于desFileSize的要求
			commpressPicCycle(desPath, desFileSize, accuracy);
		}
		
		

    //根据活动ID，获取活动信息，开放接口给客户调用
    @ApiOperation("查询活动")
    @GetMapping("/queryTask")
    public AjaxResult queryTask(String taskId) {
        /**
         * 为了防止黑客攻击，仅返回活动的最小信息量，其它无关字段不暴露
         */
        return success(buzTaskService.getBuzTaskSimple(taskId));
    }
    
  //根据openID，获取会员信息
    @ApiOperation("查询会员信息")
    @GetMapping("/queryMemberInfo")
    public AjaxResult queryMemberInfo(String openId) {
    	System.out.println("查询会员信息:/queryMemberInfo?openId="+openId);
    	if(openId==null||openId.trim().equals("")) {
    		return success(null);
    	}
    	BuzMember member=new BuzMember();
    	member.setOpenId(openId);
    	List<BuzMember> memberList=buzMemberService.selectBuzMemberList(member);
    	if(memberList!=null&&memberList.size()>0) {
    		member=memberList.get(0);
    		return success(member);
    	}else {
    		return success(null);
    	}
    }
    
  //更新会员信息
    @ApiOperation("更新会员信息")
    @PostMapping("/updateMemberInfo")
    public AjaxResult updateMemberInfo(@RequestBody BuzMember member) {

    	if(member.getOpenId()==null||member.getOpenId().trim().equals("")) {
    		return error("微信OPENID为空");
    	}
    	
    	BuzMember memberQuery=new BuzMember();
    	memberQuery.setOpenId(member.getOpenId());
    	List<BuzMember> memberList=buzMemberService.selectBuzMemberList(memberQuery);
    	if(memberList!=null&&memberList.size()>0) {
    		BuzMember member2=memberList.get(0);
    		
    		if(member2.getOrginPhone()!=null&&!member2.getOrginPhone().equals("")) {//已经改过了一次
    			//判断是否存在第二次修改用户信息
    			if(member.getPhone()!=null&&!member.getPhone().equals("")) {//如果本次号码 不为空，则判断号码与数据库里的号码是否相同，如果不相同，则是二次修改，返回错误。
    				if(!member.getPhone().equals(member2.getPhone())) {
    					return error("电话号码只能修改一次");
    				}
    			}else {
    				//本次号码为空，则说明是清除了本次号码
    				return error("电话号码只能修改一次");
    			}
    		}else {//没有改过号码，判断本次是否修改号码，如果修改号码，则把原号码字段填入
    			if(member.getPhone()!=null&&!member.getPhone().equals("")) {
    				if(!member.getPhone().equals(member2.getPhone())) {
    					member.setOrginPhone(member2.getPhone());
    				}
    			}
    		}
    		
    		member.setId(member2.getId());
    	}
    	
    	//根据OPENID查找会员ID
    	
    	return success(buzMemberService.updateBuzMember(member));
    	
    	
    }

    //根据活动ID，参加人的经纬度，开始参加活动，开放接口给客户调用
    /*
     * 1.先验证是否可以参加活动。
     * 2.如果可以参加活动，创建试卷，返回试卷信息。
     */
    @ApiOperation("用户根据活动id获取活动问题")
    @PostMapping("/startTask")
    public AjaxResult startTask(@RequestBody UserTaskAddData addData) {
    	//SysUser user = SecurityUtils.getLoginUser().getUser();
    	if(addData.getMemberId()==null) {
    		//addData.setMemberId(user.getUserName());
    		return error("无法参加活动");
    	}
    	
    	System.out.println("-----startTask----------"+addData.getMemberId()+","+addData.getLatitude()+";"+addData.getLongitude());
    	
        //验证是否可以参加活动
    	Map map=vaildCheck(addData,addData.getPreview()?addData.getPreview():false);
    	int flag=(Integer)map.get("flag");
    	String msg=(String)map.get("msg");
        if (flag==0) {
            BuzTaskAddData result = buzTaskService.userGetTaskByTaskId(addData.getTaskId(), addData.getMemberId(),addData.getLongitude(),addData.getLatitude());
            return success(result);
        } else {
            return error(msg);
        }
    }

    @GetMapping("/getAnswerByQuestionId")
    public AjaxResult getAnswerByQuestionId(String id){
        String result = buzTaskService.getAnswerByQuestionId(id);
        return success(result);
    }

    private Map vaildCheck(UserTaskAddData addData ,Boolean isPreview) {
    	
    	Map map=new HashMap();
    	
    	//判断是否预览模式
    	// 如果是则跳过活动状态判断
    	
        /**
         * 1.根据活动ID获取活动信息
         * 2.判断活动时间是否已经结束
         * 3.判断活动是否有地区限制，如果有，则根据参加人的经纬度，获取参加人所在城市，判断参加人是能参加活动
         * 4.判断活动是否有限制参加人的参与次数，是否每天有参与次数限制
         */
        BuzTask buzTask = buzTaskService.selectBuzTaskById(addData.getTaskId());

        List<BuzTaskArea> buzTaskAreas = iBuzTaskAreaService.selectBuzTaskAreaByTaskId(buzTask.getId());

        BuzMember buzMember = buzMemberService.selectBuzMemberById(addData.getMemberId());
        //活动状态,非"进行中"不可进入
        if(!isPreview) {
        	if (!"2".equals(buzTask.getStatus())) {
        		//System.out.println("非进行中");
        		map.put("flag", 1);
        		map.put("msg", "活动未发布，您无法参加！");
                return map;
            }
        }
        
        
        long betweenDay = DateUtil.between(DateUtils.getNowDate(), buzTask.getEndTime(), DateUnit.DAY, false);
        //超过活动结束时间，不可进入
        if (betweenDay < 0) {
            System.out.println("超过活动结束时间");
            map.put("flag", 1);
    		map.put("msg", "活动未开始或者活动已结束，您无法参加！");
            return map;
        }
        //地区限制
        if (buzTask.getJoinInAreaType() != 0) {
        	// 拿不到用户坐标，返回false
        	if(addData.getLongitude()==null||addData.getLatitude()==null) {
        		System.out.println("无用户坐标");
        		 map.put("flag", 1);
         		 map.put("msg", "获取不到您的坐标，请确认您的GPS定位是否已经打开！");
                 return map;
        	}
        	
        	
        	boolean isInArea = false;
        	
        	//判断该用户今天是否已经答过题，如果答过，则允许答题
        	BuzTaskUser buzTaskUser=new BuzTaskUser();
        	buzTaskUser.setMemberId(addData.getMemberId());
        	buzTaskUser.setTaskId(buzTask.getId());
        	int count=iBuzTaskUserService.getCountByTaskIdByMemberIdCurrDay(buzTaskUser);
        	if(count>0) {
        		isInArea = true;
        	}
        	
        	if (!isInArea) {
        	
	        	//判断该坐标是否已经答过题，如果答过，则允许答题
        		buzTaskUser=new BuzTaskUser();
            	buzTaskUser.setLatitude(addData.getLatitude());
            	buzTaskUser.setLongitude(addData.getLongitude());
            	buzTaskUser.setTaskId(buzTask.getId());	        	
            	count=iBuzTaskUserService.getCountByTaskIdByLongitude(buzTaskUser);
            	if(count>0) {
            		isInArea = true;
            	}
            	
            	if (!isInArea) {
            	
		            Map<String, String> userAddressMap = GeoLocationToAddress.getProvinceCityDistrictMap(Double.parseDouble(addData.getLongitude()), Double.parseDouble(addData.getLatitude()));
		            
		            for(BuzTaskArea buzTaskArea : buzTaskAreas){
		                if((userAddressMap.get(GeoLocationToAddress.PROVINCE).equals(buzTaskArea.getProvinceName()) && userAddressMap.get(GeoLocationToAddress.CITY).equals(buzTaskArea.getCityName()))){
		                    isInArea = true;
		                }
		            }
		            
		            if (!isInArea) {
		            	System.out.println("地区限制");
		            	map.put("flag", 1);
		        		map.put("msg", "您的位置不在活动允许的地区范围，请确认您的GPS定位是否已经打开！");
		                return map;
		            }
            	}
        	}
        }
        //人数限制
        if (buzTask.getJoinInType() != 0) {
            if(buzTask.getLimitMans() == iBuzTaskUserService.getCountByTaskId(buzTask.getId())){
            	map.put("flag", 1);
        		map.put("msg", "活动人数已达上限，欢迎您下次再来！");
                return map;
            }
        }
        //是否已超过参加次数
        if(buzTask.getTotalJoinTimesType() !=0 ){
            //总参与机会限制
            if(buzTask.getTotalJoinTimes() != null ){
                if(buzTask.getTotalJoinTimes() == iBuzTaskUserService.getCountByTaskIdAndUserId(buzTask.getId(), addData.getMemberId())) {
                    System.out.println("总参与机会限制");
                    map.put("flag", 1);
            		map.put("msg", "您已达到了参与次数上限，欢迎您下次再来！");
                    return map;
                }
            }
            //每日每人参与机会次数
            if(buzTask.getEveryDateJoinTimes() != null){
                if(buzTask.getEveryDateJoinTimes() == iBuzTaskUserService.getCountByTaskIdAndUserIdPerDay(buzTask.getId(), addData.getMemberId())) {
                   System.out.println("每日每人参与机会次数");
                   map.put("flag", 1);
           		   map.put("msg", "一天只能参与活动"+buzTask.getEveryDateJoinTimes()+"次，欢迎您明天再来！");
                   return map;
                }
            }
        }
        //可以参加活动，创建试卷，返回试卷信息
        map.put("flag", 0);
		map.put("msg", "能参与活动");
        return map;
    }

    @ApiOperation("用户提交保存问题")
    @PostMapping("/saveUserTaskOption")
    public AjaxResult saveUserTaskOption(@RequestBody BuzTaskAddData addData) {
    	logger.info("--------saveUserTaskOption:-------",addData);
    	System.out.println("--------saveUserTaskOption222:-------"+addData);
        BuzTaskUser result = buzTaskService.saveUserTaskOption(addData);
        return success(result);
    }
    
    @ApiOperation("用户提交练习问题")
    @PostMapping("/saveUserPraticTask")
    public AjaxResult saveUserPraticTask(@RequestBody BuzTaskAddData addData) {
        BuzTaskUser result = buzTaskService.saveUserPraticTask(addData);
        return success(result);
    }


    private Map vaildAwardsCheck(UserTaskAddData addData) {
    	
    	Map map=new HashMap();
        /**
         * 1.根据活动ID获取抽奖信息
         * 2.判断抽奖次数
         */
        BuzTask buzTask = buzTaskService.selectBuzTaskById(addData.getTaskId());
        // 直接获取用户id
        //addData.setMemberId(getUsername());
        
        
        

        BuzMember buzMember = buzMemberService.selectBuzMemberById(addData.getMemberId());
        if(buzMember==null) {
        	addData.setAwardFlag(false);
        	map.put("flag", 1);
    		map.put("msg", "您用户信息未保存，请先填写用户信息！");
            return map;
        }
        
        
        BuzTaskUser buzTaskUser =  iBuzTaskUserService.selectBuzTaskUserById(addData.getTaskUserId());
        if(buzTaskUser.getCanAwardsFlag().intValue()==0) {
        	addData.setAwardFlag(false);
        	map.put("flag", 1);
    		map.put("msg", "您未达成抽奖条件，请继续努力！");
            return map;
        }
        
        if(buzTaskUser.getAwardsTime()!=null) {
        	addData.setAwardFlag(false);
        	map.put("flag", 1);
    		map.put("msg", "您已经抽过奖，请重新答题再试一次！");
            return map;
        }
        
        //比较答题结束时间-开始时间，超过40秒，才能中奖
        if(buzTaskUser.getStartTime()!=null&&buzTaskUser.getEndTime()!=null) {
	        long chaSec=DateUtil.between(buzTaskUser.getStartTime(),buzTaskUser.getEndTime(),DateUnit.SECOND);
	        if(chaSec<35) {//调整成35秒
	        	addData.setAwardFlag(false);
	        	map.put("flag", 0);
	    		map.put("msg", "");
	            return map;
	        }
        }
        

        //总抽奖次数限制
        if (buzTask.getTotalAwardsTimesType() != 0) {
            if(buzTask.getTotalAwardsTimes() == iBuzTaskUserService.getAwardCountByTaskId(buzTask.getId())){
            	addData.setAwardFlag(false);
            	map.put("flag", 0);
        		map.put("msg", "");
                return map;
            }
        }
        //每日抽奖次数限制
        /*
        if(buzTask.getEveryDateAwardsTimes()>0&&buzTask.getEveryDateAwardsTimes() <= iBuzTaskUserService.getAwardCountByTaskIdPerDay(buzTask.getId())){
        	addData.setAwardFlag(false);
        	map.put("flag", 0);
    		map.put("msg", "");
            return map;
        }
        */
        //每人抽奖次数限制
        if(buzTask.getEveryoneCanAwardsTimes()>0&&buzTask.getEveryoneCanAwardsTimes() <= iBuzTaskUserService.getAwardCountByTaskIdAndMemberId(buzTask.getId(),buzMember.getId())){
        	addData.setAwardFlag(false);
        	map.put("flag", 0);
    		map.put("msg", "");
            return map;
        }
        //每人每日抽奖次数限制
        if(buzTask.getEveryoneEverydateAwardsType() != 0){
            if(buzTask.getEveryoneEverydateAwardsTimes() <= iBuzTaskUserService.getAwardCountByTaskIdAndMemberIdPerDay(buzTask.getId(),buzMember.getId())){
            	addData.setAwardFlag(false);
            	map.put("flag", 0);
        		map.put("msg", "");
                return map;
            }
            //跟奖项记录对比
            if(buzTask.getEveryoneEverydateAwardsTimes() <= buzTaskAwardsJackpotMapper.countAwardByTaskUserIdPerDay(addData.getTaskUserId())){
            	addData.setAwardFlag(false);
            	map.put("flag", 0);
        		map.put("msg", "");
                return map;
            }
            
            
        }
        
        
        //判断当前用户的经纬度是否已经领奖超过10次
        if(iBuzTaskUserService.getAwardCountByLongitudePerDay(addData.getTaskUserId())>=10) {
        	addData.setAwardFlag(false);
        	map.put("flag", 0);
    		map.put("msg", "");
            return map;
        }
        
        
        
        //可以参加抽奖
        addData.setAwardFlag(true);
    	map.put("flag", 0);
		map.put("msg", "");
        return map;
    }
    
    
    
    private Map vaildAwardsCheck2(UserTaskAddData addData) {
    	
    	Map map=new HashMap();
        /**
         * 1.根据活动ID获取抽奖信息
         * 2.判断抽奖次数
         */
        BuzTask buzTask = buzTaskService.selectBuzTaskById(addData.getTaskId());
        // 直接获取用户id
        //addData.setMemberId(getUsername());
        
        
        

        BuzMember buzMember = buzMemberService.selectBuzMemberById(addData.getMemberId());
        if(buzMember==null) {
        	addData.setAwardFlag(false);
        	map.put("flag", 1);
    		map.put("msg", "您用户信息未保存，请先填写用户信息！");
            return map;
        }
        
        
        BuzTaskUser buzTaskUser =  iBuzTaskUserService.selectBuzTaskUserById(addData.getTaskUserId());
        if(buzTaskUser.getCanAwardsFlag().intValue()==0) {
        	addData.setAwardFlag(false);
        	map.put("flag", 1);
    		map.put("msg", "您未达成抽奖条件，请继续努力！");
            return map;
        }
        
        if(buzTaskUser.getAwardsTime()!=null) {
        	addData.setAwardFlag(false);
        	map.put("flag", 1);
    		map.put("msg", "您已经抽过奖，请重新答题再试一次！");
            return map;
        }
        
        //比较答题结束时间-开始时间，超过40秒，才能中奖
        if(buzTaskUser.getStartTime()!=null&&buzTaskUser.getEndTime()!=null) {
	        long chaSec=DateUtil.between(buzTaskUser.getStartTime(),buzTaskUser.getEndTime(),DateUnit.SECOND);
	        if(chaSec<25) {//调整成35秒//调整成25秒
	        	addData.setAwardFlag(false);
	        	map.put("flag", 0);
	    		map.put("msg", "");
	            return map;
	        }
        }
        

        //总抽奖次数限制
        if (buzTask.getTotalAwardsTimesType() != 0) {
            if(buzTask.getTotalAwardsTimes() == iBuzTaskUserService.getAwardCountByTaskId(buzTask.getId())){
            	addData.setAwardFlag(false);
            	map.put("flag", 0);
        		map.put("msg", "");
                return map;
            }
        }
        //每日抽奖次数限制
        /*
        if(buzTask.getEveryDateAwardsTimes()>0&&buzTask.getEveryDateAwardsTimes() <= iBuzTaskUserService.getAwardCountByTaskIdPerDay(buzTask.getId())){
        	addData.setAwardFlag(false);
        	map.put("flag", 0);
    		map.put("msg", "");
            return map;
        }
        */
        //每人抽奖次数限制
        if(buzTask.getEveryoneCanAwardsTimes()>0&&buzTask.getEveryoneCanAwardsTimes() <= iBuzTaskUserService.getAwardCountByTaskIdAndMemberId(buzTask.getId(),buzMember.getId())){
        	addData.setAwardFlag(false);
        	map.put("flag", 0);
    		map.put("msg", "");
            return map;
        }
        //每人每日抽奖次数限制
        if(buzTask.getEveryoneEverydateAwardsType() != 0){
            if(buzTask.getEveryoneEverydateAwardsTimes() <= iBuzTaskUserService.getAwardCountByTaskIdAndMemberIdPerDay(buzTask.getId(),buzMember.getId())){
            	addData.setAwardFlag(false);
            	map.put("flag", 0);
        		map.put("msg", "");
                return map;
            }
            //跟奖项记录对比
            if(buzTask.getEveryoneEverydateAwardsTimes() <= buzTaskAwardsJackpotMapper.countAwardByTaskUserIdPerDay(addData.getTaskUserId())){
            	addData.setAwardFlag(false);
            	map.put("flag", 0);
        		map.put("msg", "");
                return map;
            }
            
            
        }
        
        
        //判断当前用户的经纬度是否已经领奖超过10次
        if(iBuzTaskUserService.getAwardCountByLongitudePerDay(addData.getTaskUserId())>=10) {
        	addData.setAwardFlag(false);
        	map.put("flag", 0);
    		map.put("msg", "");
            return map;
        }
        
        if(buzTaskUser.getGainTimeEnd()!=null) {                		
    		long betweenSecond = DateUtil.compare(new Date(),buzTaskUser.getGainTimeEnd());//第一个时间跟第二个时间比较，大于返回1，小于返回-1
    		if(betweenSecond>0) {//已经超过5分钟了，能参加抽奖，但是不能中奖
    			addData.setAwardFlag(false);
    			map.put("flag", 0);
        		map.put("msg", "");
    		}
    	}
        
        
        
        //可以参加抽奖
        addData.setAwardFlag(true);
    	map.put("flag", 0);
		map.put("msg", "");
        return map;
    }
    
    
    
    
    
    /*
    @ApiOperation("用户抽奖")
    @PostMapping("/getUserTaskAwards")
    public AjaxResult getUserTaskAwards(@RequestBody UserTaskAddData addData) {
    	Map map=vaildAwardsCheck(addData);
    	int flag=(Integer)map.get("flag");
    	String msg=(String)map.get("msg");
        if (flag==0) {
        	try {
	            BuzTaskUser result = buzTaskService.getUserTaskAwards(addData);
	            result.setAwardsUrl(null);
	            return success(result);
        	}catch(Exception e) {
        		return error(msg);
        	}
        }else {
            return error(msg);
        }
    }
    */


    @ApiOperation("发送短信")
    @GetMapping("/sendSms")
    public AjaxResult sendSms(String mobile, String mobileCode) {
        String phone = mobile;
        if(mobileCode==null||mobileCode.equals("")) mobileCode="8888";
        if (phone == null || phone.equals("") || phone.length() != 11
               ) {
            if (phone == null || phone.equals("") || phone.length() != 11) {
                return AjaxResult.error("手机号码为空或手机号格式不正确");
            } else {
                return AjaxResult.error("IP地址为空");
            }
        } else {
            /**
             * 1.查询该IP地址在30秒内发起短信验证次数是否超过6次（查表sys_oper_log），如果超过6次，则禁止。防止别人防止恶意刷手机验证码短信
             * 2.查询该手机号码在有效时间范围内是否有短信验证码记录（查表t_sms）。如果没有，则发送短信，并记录到表t_sms中。如果有记录，则判断发送短信时间是否超过1分钟。
             * 如果超过，则重新发送短信验证码。否则不发送验证码。
             */


            YxSms sms = new YxSms();
            sms.setMobile(phone);
            sms.setBeginTime(StringDate.getTime());
            List<YxSms> tsms = tSmsService.selectTSmsLists(sms);
            if (tsms != null && tsms.size() > 0) {
                try {
                    String nowTimeString = StringDate.getTime();
                    String beginTime = tsms.get(0).getBeginTime();
                    long cha = StringDate.getCompareDateMinu(beginTime, nowTimeString);
                    if (cha >= 1) {
                        // 间隔时间超过1分钟，发短信
                        sms = tsms.get(0);
                        String code = String.valueOf(sms.getCode());

                        //短信验证码
                        //sendSmsDemo.sendSms(phone, code);
                        smsSender.batchSendMsg(mobile, new Integer(code).toString());
                    } else {
                        return AjaxResult.error("当前操作太频繁，请稍后再试！！！");
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else {
                // 发短信

                int code = (int) ((Math.random() * 9 + 1) * 100000);
                String Code = String.valueOf(code);
                //短信验证码
                //sendSmsDemo.sendSms(phone, new Integer(code).toString());
                /**京东云短信接口代码**/
                smsSender.batchSendMsg(mobile, new Integer(code).toString());

//				smsSender.sendSms(mobile, new Integer(code).toString());
                Calendar cal = Calendar.getInstance();
                cal.setTime(new Date());
                cal.add(Calendar.MINUTE, 15);// 24小时制
                YxSms sms1 = new YxSms();
                sms1.setBeginTime(StringDate.getTime());
                sms1.setEndTime(StringDate.getTime4(cal.getTime()));
                sms1.setCode(Code);
                sms1.setMobile(phone);
                sms1.setMobileCode(mobileCode);
                tSmsService.insertYxSms(sms1);
                return AjaxResult.success("短信发送成功");
            }

        }

        return AjaxResult.success("短信发送成功");

    }
    
    
    @ApiOperation("获取领奖短信验证码")
    @GetMapping("/sendSms4Awards")
    /**
     * 
     * @param mobile 手机号码
     * @param mobileCode 随便填8888
     * @param taskId  活动ID
     * @param taskUserId  用户参加活动的ID
     * @return
     */
    public AjaxResult sendSms4Awards(String mobile, String mobileCode,String taskId,String taskUserId) {
        String phone = mobile;
        if (phone == null || phone.equals("") || phone.length() != 11
                ) {
            if (phone == null || phone.equals("") || phone.length() != 11) {
                return AjaxResult.error("手机号码为空或手机号格式不正确");
            } else {
                return AjaxResult.error("IP地址为空");
            }
        } else {
        	
        	//判断当前手机号码，当天是否已经领过奖
        	//根据手机号查找会员信息
        	BuzMember member=new BuzMember();
        	member.setPhone(mobile);
        	List<BuzMember> memberList=buzMemberService.selectBuzMemberList(member);
        	if(memberList!=null&&memberList.size()>0) {
        		member=memberList.get(0);
        		
        		BuzTaskUser buzTaskUserQuery =new BuzTaskUser();
        		buzTaskUserQuery.setTaskId(taskId);
        		buzTaskUserQuery.setMemberId(member.getOpenId());
        		Date beginOfDay = DateUtil.beginOfDay(new Date());
        		buzTaskUserQuery.setReceiveAwardsTime(beginOfDay);
        		
        		List<Map> list=iBuzTaskUserService.getTodayAwards(buzTaskUserQuery);
        		
        		System.out.println("--------今天领奖情况统计----------"+list.size());
        		
        		if(list!=null&&list.size()>0) {
        			return AjaxResult.error("您今天已经领过奖了，不能再领奖！");
        		}
        	}
        	
        	BuzTaskUser buzTaskUser =  iBuzTaskUserService.selectBuzTaskUserById(taskUserId);
            if(buzTaskUser.getCanAwardsFlag().intValue()==1&&buzTaskUser.getAwardsLevel()!=null) {
            	if(buzTaskUser.getReceiveAwardsTime()==null) {

            		Date receiveAwardsSmsTime=buzTaskUser.getReceiveAwardsSmsTime();
            		
            		if(receiveAwardsSmsTime!=null) {/*
            			String nowTimeString = StringDate.getTime();
            			long cha = StringDate.getCompareDateMinu(beginTime, nowTimeString);
                        if (cha >= 1) {//间隔超过1分钟，再 次发送短信
                        	int code = (int) ((Math.random() * 9 + 1) * 100000);
                            String Code = String.valueOf(code);
                            //短信验证码
                            sendSmsDemo.sendSms(phone, new Integer(code).toString());
                            buzTaskUser.setReceiveAwardsSms(Code);
                            buzTaskUser.setReceiveAwardsSmsTime(DateUtils.getNowDate());
                            iBuzTaskUserService.updateBuzTaskUser(buzTaskUser);
                        }else {
                        	return AjaxResult.error("当前操作太频繁，请稍后再试！！！");
                        }
                        */
            		}
            		
            		
            		int code = (int) ((Math.random() * 9 + 1) * 100000);
                    String Code = String.valueOf(code);
                    //短信验证码
                    /**阿里云短信接口代码*/
                    //sendSmsDemo.sendSms(phone, new Integer(code).toString());
                    
                    /**京东云短信接口代码**/
                    smsSender.batchSendMsg(mobile, new Integer(code).toString());
                    
                    buzTaskUser.setReceiveAwardsSms(Code);
                    buzTaskUser.setReceiveAwardsSmsTime(DateUtils.getNowDate());
                    iBuzTaskUserService.updateBuzTaskUser(buzTaskUser);
                    iBuzTaskUserService.nullReceiveAwardsTime(buzTaskUser);
                    
                    
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(new Date());
                    cal.add(Calendar.MINUTE, 15);// 24小时制
                    YxSms sms1 = new YxSms();
                    sms1.setBeginTime(StringDate.getTime());
                    sms1.setEndTime(StringDate.getTime4(cal.getTime()));
                    sms1.setCode(Code);
                    sms1.setMobile(phone);
                    sms1.setMobileCode(mobileCode);
                    tSmsService.insertYxSms(sms1);
                    
                    
            	}else {
            		return AjaxResult.error("您已经领过奖了，不能重复领奖！");
            	}
            }else {
            	return AjaxResult.error("您不满足领奖，不能领奖！");
            }


        }

        return AjaxResult.success("短信发送成功");

    }
    
    
    @ApiOperation("获取抽奖短信验证码")
    @GetMapping("/sendSms4Gain")
    /**
     * 
     * @param mobile 手机号码
     * @param mobileCode 随便填8888
     * @param taskId  活动ID
     * @param taskUserId  用户参加活动的ID
     * @return
     */
    public AjaxResult sendSms4Gain(String mobile, String mobileCode,String taskId,String taskUserId) {
        String phone = mobile;
        if (phone == null || phone.equals("") || phone.length() != 11
                ) {
            if (phone == null || phone.equals("") || phone.length() != 11) {
                return AjaxResult.error("手机号码为空或手机号格式不正确");
            } else {
                return AjaxResult.error("IP地址为空");
            }
        } else {
        	
        	//判断当前手机号码，当天是否已经领过奖
        	//根据手机号查找会员信息
        	BuzMember member=new BuzMember();
        	member.setPhone(mobile);
        	List<BuzMember> memberList=buzMemberService.selectBuzMemberList(member);
        	if(memberList!=null&&memberList.size()>0) {
        		member=memberList.get(0);
        		
        		BuzTaskUser buzTaskUserQuery =new BuzTaskUser();
        		buzTaskUserQuery.setTaskId(taskId);
        		buzTaskUserQuery.setMemberId(member.getOpenId());
        		Date beginOfDay = DateUtil.beginOfDay(new Date());
        		buzTaskUserQuery.setReceiveAwardsTime(beginOfDay);
        		
        		List<Map> list=iBuzTaskUserService.getTodayAwards(buzTaskUserQuery);
        		
        		System.out.println("--------今天领奖情况统计----------"+list.size());
        		
        		if(list!=null&&list.size()>=2) {
        			return AjaxResult.error("您今天已经领过奖了，不能再抽奖！");
        		}
        	}
        	
        	BuzTaskUser buzTaskUser =  iBuzTaskUserService.selectBuzTaskUserById(taskUserId);
            if(buzTaskUser.getCanAwardsFlag().intValue()==1&&buzTaskUser.getAwardsLevel()==null) {
            	if(buzTaskUser.getGainAwardsSmsTime()==null) {

            		Date receiveAwardsSmsTime=buzTaskUser.getGainAwardsSmsTime();
            		
            		if(receiveAwardsSmsTime!=null) {/*
            			String nowTimeString = StringDate.getTime();
            			long cha = StringDate.getCompareDateMinu(beginTime, nowTimeString);
                        if (cha >= 1) {//间隔超过1分钟，再 次发送短信
                        	int code = (int) ((Math.random() * 9 + 1) * 100000);
                            String Code = String.valueOf(code);
                            //短信验证码
                            sendSmsDemo.sendSms(phone, new Integer(code).toString());
                            buzTaskUser.setReceiveAwardsSms(Code);
                            buzTaskUser.setReceiveAwardsSmsTime(DateUtils.getNowDate());
                            iBuzTaskUserService.updateBuzTaskUser(buzTaskUser);
                        }else {
                        	return AjaxResult.error("当前操作太频繁，请稍后再试！！！");
                        }
                        */
            		}
            		
            		
            		int code = (int) ((Math.random() * 9 + 1) * 100000);
                    String Code = String.valueOf(code);
                    //短信验证码
                    /**阿里云短信接口代码*/
                    //sendSmsDemo.sendSms(phone, new Integer(code).toString());
                    
                    /**京东云短信接口代码**/
                    smsSender.batchSendMsg(mobile, new Integer(code).toString());
                    
                    
                    Date awardsDate = DateUtils.getNowDate();
                	Date awardsTimeEnd=DateUtil.offsetMinute(awardsDate, 1);
                    
                    buzTaskUser.setGainAwardsSms(Code);
                    buzTaskUser.setGainAwardsSmsTime(DateUtils.getNowDate());
                    buzTaskUser.setGainTimeEnd(awardsTimeEnd);
                    iBuzTaskUserService.updateBuzTaskUser(buzTaskUser);
                    
                    
                    
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(new Date());
                    cal.add(Calendar.MINUTE, 15);// 24小时制
                    YxSms sms1 = new YxSms();
                    sms1.setBeginTime(StringDate.getTime());
                    sms1.setEndTime(StringDate.getTime4(cal.getTime()));
                    sms1.setCode(Code);
                    sms1.setMobile(phone);
                    sms1.setMobileCode(mobileCode);
                    tSmsService.insertYxSms(sms1);
                    
                    
            	}else {
            		return AjaxResult.error("您已经抽过奖了，不能重复抽奖！");
            	}
            }else {
            	return AjaxResult.error("您不满足抽奖条件，不能抽奖！");
            }


        }

        return AjaxResult.success("短信发送成功");

    }
    
    @ApiOperation("提交短信验证码领奖")
    @GetMapping("/submitSms4Awards")
    /**
     * 
     * @param mobile  手机号码
     * @param code    收到的短信验证码
     * @param taskId  活动ID
     * @param taskUserId  用户参加活动的ID
     * @return
     */
    public AjaxResult submitSms4Awards(String mobile, String code,String taskId,String taskUserId,String openId) {

    	String phone = mobile;
        if (phone == null || phone.equals("") || phone.length() != 11
                || code == null || code.equals("")) {
            if (phone == null || phone.equals("") || phone.length() != 11) {
                return AjaxResult.error("手机号码为空或手机号格式不正确");
            } else {
                return AjaxResult.error("IP地址为空");
            }
        } else {
        	BuzTaskUser buzTaskUser =  iBuzTaskUserService.selectBuzTaskUserById(taskUserId);
        	
        	//System.out.println("88888888888888888888openId888888888="+openId+",MemberId-----------="+buzTaskUser.getMemberId());
        	if(buzTaskUser.getAwardsTimeEnd()!=null) {
        		
        		long betweenSecond = DateUtil.compare(new Date(),buzTaskUser.getAwardsTimeEnd());//第一个时间跟第二个时间比较，大于返回1，小于返回-1
        		if(betweenSecond>0) {//已经超过5分钟了，不能领奖
        			return AjaxResult.success();
        		}
        		
        		/*
        		long betweenSecond = DateUtil.between( new Date(),buzTaskUser.getAwardsTimeEnd(), DateUnit.SECOND);
        		if(betweenSecond>0) {//已经超过5分钟了，不能领奖
        			return AjaxResult.success();
        		}
        		*/
        	}
        	/*
        	if(!buzTaskUser.getMemberId().equals(openId)) {
        		return AjaxResult.error("您不满足领奖，不能领奖！");
        	}
        	*/
        	
            if(buzTaskUser.getCanAwardsFlag().intValue()==1&&buzTaskUser.getAwardsLevel()!=null) {
            	if(buzTaskUser.getReceiveAwardsTime()==null) {
            		if(code.equals(buzTaskUser.getReceiveAwardsSms())) {//短信验证码正确
            			//验证该短信验证码的时效性
            			YxSms yxSms=new YxSms();
            			yxSms.setMobile(mobile);
            			yxSms.setCode(code);
            			yxSms.setBeginTime(DateUtil.now());
            			yxSms.setEndTime(DateUtil.now());
            			List<YxSms> smsList= tSmsService.selectTSmsLists(yxSms);
            			if(smsList.size()>0) {//在时效范围内
            				//buzTaskUser.setReceiveAwardsSmsTime(DateUtils.getNowDate());
                            iBuzTaskUserService.updateReceiveAwardsTime(buzTaskUser);
                            //发奖
                            iBuzTaskUserService.sendWards(buzTaskUser,openId);
                			return AjaxResult.success();
            			}else {
            				return AjaxResult.error("验证码异常！");
            			}
            			
            		}else {
            			return AjaxResult.error("验证码不正确，请确认后再试！");
            		}
            	}else {
            		return AjaxResult.error("您已经领过奖了，不能重复领奖！");
            	}
            }else {
            	return AjaxResult.error("您不满足领奖，不能领奖！");
            }
        }
    }
    
    @ApiOperation("无需短信验证码领奖")
    @GetMapping("/submitAwards")
    /**
     * 
     * @param mobile  手机号码
     * @param code    收到的短信验证码
     * @param taskId  活动ID
     * @param taskUserId  用户参加活动的ID
     * @return
     */
    public AjaxResult submitAwards(String taskId,String taskUserId,String openId) {

    	
        	BuzTaskUser buzTaskUser =  iBuzTaskUserService.selectBuzTaskUserById(taskUserId);
        	
        	//System.out.println("88888888888888888888openId888888888="+openId+",MemberId-----------="+buzTaskUser.getMemberId());
        	if(buzTaskUser.getAwardsTimeEnd()!=null) {
        		
        		long betweenSecond = DateUtil.compare(new Date(),buzTaskUser.getAwardsTimeEnd());//第一个时间跟第二个时间比较，大于返回1，小于返回-1
        		if(betweenSecond>0) {//已经超过5分钟了，不能领奖
        			return AjaxResult.success();
        		}
        		
        		/*
        		long betweenSecond = DateUtil.between( new Date(),buzTaskUser.getAwardsTimeEnd(), DateUnit.SECOND);
        		if(betweenSecond>0) {//已经超过5分钟了，不能领奖
        			return AjaxResult.success();
        		}
        		*/
        	}
        	/*
        	if(!buzTaskUser.getMemberId().equals(openId)) {
        		return AjaxResult.error("您不满足领奖，不能领奖！");
        	}
        	*/
        	
            if(buzTaskUser.getCanAwardsFlag().intValue()==1&&buzTaskUser.getAwardsLevel()!=null) {
            	if(buzTaskUser.getReceiveAwardsTime()==null) {
                iBuzTaskUserService.updateReceiveAwardsTime(buzTaskUser);
                //发奖
                iBuzTaskUserService.sendWards(buzTaskUser,openId);
    			return AjaxResult.success();

            	}else {
            		return AjaxResult.error("您已经领过奖了，不能重复领奖！");
            	}
            }else {
            	return AjaxResult.error("您不满足领奖，不能领奖！");
            }
    }
    
    @ApiOperation("提交短信验证码抽奖")
    @GetMapping("/submitSms4Gain")
    /**
     * 
     * @param mobile  手机号码
     * @param code    收到的短信验证码
     * @param taskId  活动ID
     * @param taskUserId  用户参加活动的ID
     * @return
     */
    public AjaxResult submitSms4Gain(String mobile, String code,String taskId,String taskUserId) {

    	String phone = mobile;
        if (phone == null || phone.equals("") || phone.length() != 11
                || code == null || code.equals("")) {
            if (phone == null || phone.equals("") || phone.length() != 11) {
                return AjaxResult.error("手机号码为空或手机号格式不正确");
            } else {
                return AjaxResult.error("IP地址为空");
            }
        } else {
        	BuzTaskUser buzTaskUser =  iBuzTaskUserService.selectBuzTaskUserById(taskUserId);
        	
        	
        	if(buzTaskUser.getCanAwardsFlag().intValue()==1) {
        	
        		if(buzTaskUser.getGainAwardsSmsTime()!=null) {//已经发生了抽奖短信
        			
        			
        			if(code.equals(buzTaskUser.getGainAwardsSms())) {//短信验证码正确
        				
        				//验证抽奖
        				UserTaskAddData addData=new UserTaskAddData();
        				addData.setMemberId(buzTaskUser.getMemberId());
        				addData.setTaskId(taskId);;
        				addData.setTaskUserId(taskUserId);
        				
        				Map map=vaildAwardsCheck2(addData);
        				
        				
        				int flag=(Integer)map.get("flag");
        		    	String msg=(String)map.get("msg");
        		        if (flag==0) {
        		        	try {
        			            BuzTaskUser result = buzTaskService.getUserTaskAwards(addData);
        			            result.setAwardsUrl(null);
        			            return success(result);
        		        	}catch(Exception e) {
        		        		return error(msg);
        		        	}
        		        }else {
        		            return error(msg);
        		        }

            			
            			
            		}else {
            			return AjaxResult.error("验证码不正确，请确认后再试！");
            		}
        			
        			
            		
            	}else {//没有发生抽奖短信
            		return AjaxResult.error("您不能抽奖！");
            	}
            }else {
            	return AjaxResult.error("您不满足抽奖条件，不能抽奖！");
            }
        }
    }


	@ApiOperation("微信JS-SDK权限注入")
    @GetMapping("/WxJsSdkConfig")
    public AjaxResult WxJsSdkConfig(String webUrl) throws UnsupportedEncodingException
    {
		//玉林乐居
		//String appID = "wx092325b7bcb886eb";
		//String appsecret = "af6b07ad8ead9cb7c043dba69b138b18";

		System.out.println("-------------webUrl---orgin---------------"+webUrl);
		webUrl= URLDecoder.decode(webUrl, "UTF-8");
		System.out.println("-------------webUrl---decode---------------"+webUrl);

		//植物园
		String appID = "wx63f3c4d9b2a5762f";
		String appsecret = "e0b733b036f7da675bb1ca1c2f059f74";
		
		
		//极点传媒
		//String appID = "wxe0a1755d6e3c2afd";
		//String appsecret = "17c299c5f80431b5771caacd692ec090";
		//飞标科技
		//String appID = "wxef2a4572cba58836";
		//String appsecret = "58a439eb2ad6c0694cf43c2369588591";
		
		
		//String appID = "wxe92cf6f3e91bfbf7";
		//String appsecret = "e5752bfe7764bc3c54838db00861d2ff";
		String access_token = "";
		String grant_type = "client_credential";//获取access_token填写client_credential
		//这个url链接地址和参数皆不能变
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + appID + "&secret=" + appsecret;

		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			System.out.println("JSON字符串：" + demoJson);
			access_token = demoJson.getString("access_token");
			is.close();
		} catch (Exception e) {
			logger.error("call getAccessToken error",e);
		}


		String jsapi_ticket = null;
		//这个url链接和参数不能变
		url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ access_token +"&type=jsapi";

		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			System.out.println("JSON字符串："+demoJson);
			jsapi_ticket = demoJson.getString("ticket");
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		long timeStampSec = System.currentTimeMillis()/1000;
		String timestamp = String.format("%010d", timeStampSec);//当前时间戳
		String nonceStr = StringUtils.getRandomStr(8);//	随机数
		String[] signArr = new String[]{ "jsapi_ticket=" + jsapi_ticket, "noncestr=" + nonceStr, "timestamp=" + timestamp,"url=" + webUrl};
		//System.out.println("-------------------------------");
		//System.out.println("jsapi_ticket"+jsapi_ticket+";noncestr="+nonceStr+"timestamp="+timestamp+"url="+webUrl);
		//System.out.println("-------------------------------");
		Arrays.sort(signArr);
		String signStr = StringUtils.join(signArr, "&");
		System.out.println("-------------------------------");
		System.out.println(signStr);
		System.out.println("-------------------------------");
		String signature = DigestUtils.sha1Hex(signStr);//加密


		Map map = new HashMap();
		map.put("appId", appID);
		map.put("timestamp", timestamp);
		map.put("nonceStr", nonceStr);
		map.put("signature", signature);

        return AjaxResult.success(map);
    }
	
	// 返回appSetting 信息 
	@GetMapping("/getAppSetting")
	public AjaxResult getAppSetting(String taskId) {
		System.out.println(taskId);
		
		BuzTask task =  buzTaskService.selectBuzTaskById(taskId);
		
		if(task!=null) {
			String appSetting = task.getAppSetting();
			JSONObject settingJson = JSONObject.parseObject(appSetting);
			return success(settingJson);
		}else {
			return success("");
		}
		
		
	}
	/*TODO 获取中奖信息*/
	/*
	@GetMapping("/getAwardsInfoByTask")
	public AjaxResult getAwardsInfoByTask(String taskId) {
		SysUser user = SecurityUtils.getLoginUser().getUser();
		System.out.println(user.getUserId());
		BuzTaskUser buzTaskUserQuery=new BuzTaskUser();
		buzTaskUserQuery.setTaskId(taskId);
		//buzTaskUserQuery.set
		List<BuzTaskUser> list= iBuzTaskUserService.selectBuzTaskUserList(buzTaskUserQuery);
		
		return success(list);
	}
	*/
	
	/*TODO 根据taskId获取中奖信息列表*/	
	@GetMapping("/getAwardsInfoByTask")
	public AjaxResult getAwardListByTask(String taskId, String userId) {
		return success(iBuzTaskUserService.getTaskAwardsInfoByTask(taskId, userId));
	}
	
	
	/*TODO 根据taskId获取答题记录列表*/	
	@GetMapping("/getSubmitListByTask")
	public AjaxResult getSubmitListByTask(String taskId, String userId) {
		return success(iBuzTaskUserService.getSubmitListByTask(taskId, userId));
	}
	
	/*TODO 分享*/	
	@GetMapping("/share")
	public AjaxResult share(String taskId, String openId) {
		
		String url="http://fkh5.gxjiankang.cn/index/"+taskId;
		String shareUrl="";
		try {
			
			BuzTask  task=buzTaskService.selectBuzTaskById(taskId);
			
			QRCodeCreate qrCodeCreate = new QRCodeCreate();
			shareUrl = qrCodeCreate.addTextCodeCreteByCreateDept(url, taskId,
					RuoYiConfig.getUploadPath(), task.getTitle(),"");
			System.out.println(shareUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return success(shareUrl);
	}
	
	
	/*TODO 根据taskId获取中奖信息列表*/	
	@GetMapping("/getAwardsInfoByTaskIdAndOpenId")
	public AjaxResult getAwardsInfoByTaskIdAndOpenId(String taskId, String openId) {
		
		if(openId==null||openId.trim().equals("")) {
    		return error("微信OPENID为空");
    	}
		
		if(taskId==null||taskId.trim().equals("")) {
    		return error("活动ID为空");
    	}
    	/*
		String userId="";
    	BuzMember memberQuery=new BuzMember();
    	memberQuery.setOpenId(openId);
    	List<BuzMember> memberList=buzMemberService.selectBuzMemberList(memberQuery);
    	if(memberList!=null&&memberList.size()>0) {
    		BuzMember member2=memberList.get(0);
    		userId=member2.getId();
    	}
    	
    	if(userId==null||userId.trim().equals("")) {
    		return error("会员信息为空");
    	}
    	*/
		
		return success(iBuzTaskUserService.getTaskAwardsInfoByTask(taskId, openId));
	}

	/**
	 * 活动统计
	 * @param taskId
	 * @return
	 * 前台决定是否需要统计条数，由于数据量的问题，统计条数将耗费相当长的时间
	 */
    @GetMapping("/getAwardsTj")
    public AjaxResult getAwardsTj(String taskId,Integer pageNum,Integer pageSize,Boolean isCount){
        // return success(iBuzTaskUserService.getTaskAwardsTjResult(taskId));
    	return success(iBuzTaskUserService.getTaskAwardsTjResult(taskId,pageNum,pageSize,isCount));
    }
    /**
     * 获取所有获奖数据(前台导出数据使用)
     * */
    @GetMapping("/getAllAwards")
    public AjaxResult getAllAwardsByTaskId(String taskId) {
    	
    	List<BuzTaskAwardsTj>  allresult =  iBuzTaskUserService.getAllTaskAwardsResult(taskId);
    	return success(allresult);
    }
    
   
    
    /*
     * 答题统计
     */
    @GetMapping("/getExamTj")
    public AjaxResult getExamTj(String taskId){
        return success(iBuzTaskUserService.getTaskAwardsTjResult(taskId));
    }
	
    //学习园地列表
    @GetMapping("/getNewsByTask")
	public AjaxResult getNewsByTask(String taskId) {
    	
    	BuzNews buzNews=new BuzNews();
    	buzNews.setTaskId(taskId);
    	buzNews.setStatus(1);
    	
    	List<BuzNews> list=buzNewsService.selectBuzNewsList(buzNews);
    	for(int i=0;i<list.size();i++) {
    		BuzNews buzNews2=list.get(i);
    		buzNews2.setContext(null);
    	}
    	
		return success(list);
	}
    
    //根据资讯ID，获取资讯详情
    @GetMapping("/viewNewsById")
	public AjaxResult viewNewsById(Long newsId,String openId) {
    	
    	BuzNews buzNews=buzNewsService.selectBuzNewsById(newsId);
    	    	
		return success(buzNews);
	}
    
    /**根据id统计数据 多线程*/
    @GetMapping("/statisticsByTaskId")
    public AjaxResult getStatisticsByTaskId(String taskId) {
    	
    	Map<String, Object> res =  iBuzTaskUserService.getStatisticsByTaskId(taskId);
    	
    	
    	return success(res);
    }
    // 获奖统计
    @GetMapping("/statisticsAwardByTaskId")
    public AjaxResult getStatisticsAwardsByTaskId(String taskId) {
    	
    	Map<String, Object> res =  iBuzTaskUserService.getStatisticsAwardsByTaskId(taskId);
    	
    	
    	return success(res);
    }
    
}
